import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

export interface ServiceResponse<T>{
  code:number,
  data:T,
  msg:string
}

//登录接口
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 10*1000,
})
//请求工具函数
export const request =<T>(url:string, method:Method ='GET', submitData?:object)=>{
  return service.request<T,ServiceResponse<T>>({
    url:url,
    method:method,
    [method.toUpperCase() ==='GET' ? 'params':'data']:submitData
  })
}
//请求拦截器
service.interceptors.request.use(
  config => {
    const {token}=useUserStore()
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
//响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.response){
      ElMessage.error(error.response.data.msg)
    }if(error.response.status===401){
      ElMessage.error('登录信息失效，请重新登录')
      router.push('/login')
      const store = useUserStore()
      store.removeToken()
    }
    else{
      ElMessage.error('网络异常，请求失败')
    }
    return Promise.reject(error)
  },
)

export default service
